package com.example.yuanboot.common.util;

import com.example.yuanboot.model.vo.jwt.SysUserInfo;

import java.util.Set;

/**
 * 全局用户信息
 *
 * @author qingyan 2021-07-22
 */
public class UserUtils {
    // 监控
    //线程变量，存放user实体类信息，即使是静态的与其他线程也是隔离的
    private final static ThreadLocal<SysUserInfo> userThreadLocal = new ThreadLocal<>();

    public static Long getUserId(){
        SysUserInfo user = userThreadLocal.get();
        if (user != null && user.getUserId() != null) {
            return user.getUserId();
        }
        return null;
    }

    public static String getUsername(){
        SysUserInfo user = userThreadLocal.get();
        if (user != null && user.getUsername() != null) {
            return user.getUsername();
        }
        return null;
    }
    public static Set<String> getRoles(){
        SysUserInfo user = userThreadLocal.get();
        if (user != null && user.getAuthorities() != null) {
            return user.getAuthorities();
        }
        return null;
    }

    public static void remove(){
        userThreadLocal.remove();
    }

    public static void saveInfo(SysUserInfo info){
        if (userThreadLocal.get() != null) {
            userThreadLocal.remove();
        }
        userThreadLocal.set(info);
    }

}
